package com.tree.common.util;

import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.IOException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @ClassName com.demo.common.util
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-05-26 22:09
 * @Version 1.0
 */
public class RSAUtil {

    public static final String ALGORITHM_RSA = "RSA";

    public static KeyPair genKeyPair(int length)throws Exception{
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(length);
        return keyPairGenerator.generateKeyPair();
    }

    public static String encrypt(String content, String publicKey) throws Exception{
        if(StringUtils.isEmpty(content) || StringUtils.isEmpty(publicKey)){
            return null;
        }
        byte[] encryptBytes = encrypt(content.getBytes(),publicKey);
        return  Base64.getEncoder().encodeToString(encryptBytes);
    }
    public static byte[] encrypt(byte[] content, String publicKey) throws Exception {
        PublicKey pubKey = getPublicKey(publicKey);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE,pubKey);
        return cipher.doFinal(content);
    }

    public static String decrypt(String content, String privateKey) throws Exception{
        if(StringUtils.isEmpty(content) || StringUtils.isEmpty(privateKey)){
            return null;
        }
        byte[] decryptBytes = decrypt(Base64.getDecoder().decode(content),privateKey);
        return new String(decryptBytes);
    }

    public static byte[] decrypt(byte[] content, String privateKey) throws Exception{
        PrivateKey priKey = getPrivateKey(privateKey);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE,priKey);
        return cipher.doFinal(content);
    }

    private static PublicKey getPublicKey(String publicKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
        return keyFactory.generatePublic(keySpec);
    }

    private static PrivateKey getPrivateKey(String privateKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 字节数组转Base64编码
     */
    public static String byte2Base64(byte[] bytes){
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    /**
     *
     * Base64编码转字节数组
     */
    public static byte[] base642Byte(String base64Key) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(base64Key);
    }

    public static void main(String[] args) throws Exception{
        KeyPair keyPair = genKeyPair(512);

        PublicKey publicKey = keyPair.getPublic();
        System.err.println("public key:"+ new String(Base64.getEncoder().encode(publicKey.getEncoded())));

        PrivateKey privateKey = keyPair.getPrivate();
        System.err.println("private key:"+ new String(Base64.getEncoder().encode(privateKey.getEncoded())));

        String encryptStr = encrypt("aaaaa888", new String(Base64.getEncoder().encode(publicKey.getEncoded())));

        System.err.println("加密后："+ encryptStr);

        String decryptStr = decrypt(encryptStr,new String(Base64.getEncoder().encode(privateKey.getEncoded())));
        System.err.println("解密后："+ decryptStr);

    }



}
